// pages/login/login.js
var app = getApp();
// const http = require('../utils/request/http');
import http from '../../utils/http.js';
import util from '../../utils/util'

import {
  GetStoreUserHomeApi
} from "../../utils/api.js"

import {
  siteMobileLoginApi,
  siteSendApi
} from "../../utils/newApi.js"


Page({

  /**
   * 页面的初始数据
   */
  data: {
    mobile:'',
    inputCode:'',
    TimeIntval:60,
    sendFlag:false,
    timer:{},
    phoneFlag:false,

    checked:false,
    activeRadio:false,
  },
  // 点击同意切换
  checkMed(){		
    this.setData({
      activeRadio: !this.data.activeRadio,
    });
  },
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
   onLoad: function (options) {
    let that = this;
    // if (!wx.getStorageSync('accessToken')) {
    //   // 没有本地accessToken
    // } else {
    //   GetStoreUserHomeApi().then(res=>{
    //       if (res.code === 200) {
    //         wx.redirectTo({
    //           url: '/pages/index/index'
    //         })
    //       }
    //   }).catch(() => {
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideHomeButton()
  },
 //跳转外部链接
 jumpAccount(e){
  wx.setStorageSync('webUrl',e.currentTarget.dataset.weburl)
  wx.navigateTo({
    url: e.currentTarget.dataset.url
  })
},
  getMobile(e){
    this.setData({
      mobile : e.detail.value
    })
    if(this.data.mobile.length === 11) {
      this.phoneExc()
    }
  },

  phoneExc(){
    let that = this;
    if(that.data.mobile){
      let phoneFlag = /^(0|86|17951)?(10[0-9]|11[0-9]|12[0-9]|13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$/.test(that.data.mobile);
      that.setData({
        phoneFlag:phoneFlag
      })
      if(!phoneFlag){
        wx.showToast({
          title: '请输入正确的手机号',
          icon:"none",
          duration:2000
        })
      }
    }
  },

  getCode(e){
    this.setData({
      inputCode : e.detail.value
    })
  },

  // 登录
  loginMed(){
    let that = this
    let mobile = that.data.mobile
    let code = that.data.inputCode
    let parms = {
      'mobile':mobile,
      'code':code,
      'platform':'store'
    };
    if(!this.data.activeRadio){
      wx.showToast({
        title: "请阅读并同意用户隐私协议",
        icon: "none",
        duration: 2000
      })
      return;
    }
    if (that.data.phoneFlag) {
      that.showMessage(function() {
        that.showMessage(function(){})
      })
      wx.login({
        success (res) {
          const code = res.code
          siteMobileLoginApi(parms).then(res=>{
            if (res.code === 0) {
              clearInterval(that.data.timer)
              util.setStorageSync('userInfo',res.data)
              util.setStorageSync('shopInfo',res.data)
              util.setStorageSync('gfnFlag', 1)
              console.log(res.data)
              app.globalData.accessToken = res.data.token
              util.setStorageSync('accessToken', res.data.token)
              wx.redirectTo({
                url: '/pages/index/index'
              })
            } else {
              clearInterval(that.data.timer)
              that.setData({
                inputCode: '',
                TimeIntval: 60,
                sendFlag: false
              })
              wx.showToast({
                title: res.message,
                icon:'none'
              }, 3000)
            }
          })
          // http.post('/api/store/v1/user/login', parms, {
          //   'content-type': 'application/json;charset=utf-8'
          // }).then(res => {
          //   if (res.code === 200) {
          //     http.post('/api/store/v1/user/update', {
          //       code,
          //       id: res.data.id
          //     }, {
          //       'content-type': 'application/json;charset=utf-8'
          //     }).then(res => {
          //     })
          //     clearInterval(that.data.timer)
          //     util.setStorageSync('userInfo',res.data)
          //     util.setStorageSync('shopInfo',res.data)
          //     util.setStorageSync('gfnFlag', 1)
          //     console.log(res.data)
          //     app.globalData.accessToken = res.data.accessToken
          //     util.setStorageSync('accessToken', res.data.accessToken)
          //     wx.redirectTo({
          //       url: '/pages/index/index'
          //     })
          //   } else {
          //     clearInterval(that.data.timer)
          //     that.setData({
          //       inputCode: '',
          //       TimeIntval: 60,
          //       sendFlag: false
          //     })
          //     wx.showToast({
          //       title: res.message,
          //       icon:'none'
          //     }, 3000)
          //   }
          // }).catch(() => {
          // })
        }
      })
    } else {
      wx.showToast({
        title: "请输入正确手机号",
        icon: "none",
        duration: 2000
      })
    }
  },

  // 手机验证码发送
  sendCode(){
    let that = this;
    let second = that.data.TimeIntval;
    if(that.data.mobile.length == 11){
      that.setData({
        sendFlag : true
      })
      siteSendApi({mobile:that.data.mobile,event:'login'}).then(res=>{
        let time = setInterval(function() {
          second--
          that.setData({
            TimeIntval: second
          })
          if (that.data.TimeIntval <= 0) {
            clearInterval(time)
            that.setData({
              sendFlag: false,
              TimeIntval: 60
            })
          }
        }, 1000)
        that.setData({
          timer: time 
        })
      })


      // http.post('/api/sms/v1/send/captcha', {
      //   phone: that.data.mobile
      // }, {
      //   'content-type': 'application/json;charset=utf-8'
      // }).then(res => {
      //   let time = setInterval(function() {
      //   second--
      //   that.setData({
      //     TimeIntval: second
      //   })
      //   if (that.data.TimeIntval <= 0) {
      //     clearInterval(time)
      //     that.setData({
      //       sendFlag: false,
      //       TimeIntval: 60
      //     })
      //   }
      // }, 1000)
      // that.setData({
      //   timer: time 
      // })
      // }).catch(error => {
      //   wx.showToast({
      //     icon: 'none',
      //     title: '发送失败',
      //   })
      // })
    } else {
      wx.showToast({
        title: "请输入正确手机号",
        icon: "none",
        duration: 2000
      })
    }
  },

  showMessage(resolve){
    let that = this
    wx.requestSubscribeMessage({
      tmplIds: ['KAytSd61RbmfPvZ6s-mBtkLwriR0uzPUzCFlioCMyzg', '3xPqcPo2_yMAuRekmENnh58HdHcT0lefR-AwBndy-qI'],
      success(res) {
        wx.getSetting({
          withSubscriptions:true,
          success(suc) {
          }
        })
      },
      complete (res) {
        switch(res['KAytSd61RbmfPvZ6s-mBtkLwriR0uzPUzCFlioCMyzg', '3xPqcPo2_yMAuRekmENnh58HdHcT0lefR-AwBndy-qI']){
          case "accept":
            wx.getSetting({
              withSubscriptions:true,
              success(suc) {
              }
            })
            break;
          case "reject":
              // 拒绝授权订阅消息
              wx.showModal({
                content: '拒绝授权后将收不到用户预定通知哦,请再次授权',
                title: '提示',
                success(res){
                  console.log('再次授权')
                  if(res.confirm){
                   console.log('再次授权成功')
                  }else{
                     console.log('再次授权失败')

                    resolve();
                  }
                }
              })
            break;
        }
      },
    })
  }
})